<template>
  <div class="bgc-default pad-20">
    <h2>基本信息</h2>
    <div class="bg-color-white pad-b-20">
      <el-form :model="action" label-position="right" label-width="233px" :rules="rules" ref="action" class="pad-t-20 pad-b-30">
        <div>
          <el-form-item label="活动名称：" prop="actionName" class="mar-t-20">
            <div class="width-per-50"><el-input v-model="action.actionName" maxlength="10" style="width:300px;"></el-input></div>
          </el-form-item>
          <el-form-item label="活动时间：" prop="actionTimeArray">
            <div class="width-per-50">
              <el-date-picker
                v-model="action.actionTimeArray"
                type="datetimerange"
                range-separator="至"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
              <div v-if="action.actionType == 10" class="font-12">新客指第一次进入店铺，并完成小程序授权的顾客，每位新客在活动期间内只能领取一次。</div>
            </div>
          </el-form-item>
          <el-form-item v-if="action.actionType == 20" label="发放条件：" prop="buyType">
            <div class="width-per-50">
              <div><el-radio v-model="action.buyType" @change="changeBuyType" label="1">首单发放</el-radio></div>
              <el-radio v-model="action.buyType" @change="changeBuyType" label="2">
                <span>单笔订单商品金额满</span>
                <el-input v-model="action.fullAmount" @keyup.native="action.fullAmount = checkInputNum(action.fullAmount)" style="width: 40%;" maxlength="10">
                  <template slot="append">元</template>
                </el-input>
                <span>（不含运费）发放一次</span>
              </el-radio>
              <div><el-radio v-model="action.buyType" @change="changeBuyType" label="3">单笔订单购买指定商品</el-radio><el-button type="text" @click="selectGoodsVisible=true" :disabled="buyTypeGoodsDisabled">选择商品</el-button></div>
            </div>
          </el-form-item>
          <el-form-item v-if="action.actionType == 20" label="发放限制：" prop="usedFlag">
            <div class="width-per-50">
              <el-checkbox v-model="action.usedFlag" true-label="0" false-label="1">已使用券的订单不发放</el-checkbox>
            </div>
          </el-form-item>
          <el-form-item v-if="action.actionType == 30" label="发放人群：" prop="customerType">
            <div class="width-per-50">
              <div><el-radio v-model="action.customerType" label="1">所有顾客</el-radio></div>
              <div><el-radio v-model="action.customerType" label="2">仅注册的顾客</el-radio></div>
              <div><el-radio v-model="action.customerType" label="3">有成交的顾客</el-radio></div>
              <div><el-radio v-model="action.customerType" label="4">指定用户</el-radio>
              <span v-if="action.customerType === '4'">
                <el-button type="text" @click="selectMemberVisible=true">选择用户</el-button>
              <span>已选择{{action.memberIds.length}}人</span>
              </span>
              </div>
              
            </div>
          </el-form-item>
          <el-form-item v-if="action.actionType == 30" label="发放方式：" prop="releaseType">
            <div class="width-per-50">
              <el-radio v-model="action.releaseType" label="1">直接到账</el-radio>
              <div class="font-12">选择直接到账，按照“发放次数”规则，直接将优惠券发放到符合条件的顾客账户。</div>
              <el-radio v-model="action.releaseType" label="2">自行领取</el-radio>
              <div class="font-12">选择自行领取，不受“发放次数”规则影响，仅将券发放至领券中心，顾客到领券中心自行领取。</div>
            </div>
          </el-form-item>
          <el-form-item v-if="action.actionType == 30 && action.releaseType == 2" label="每人限领次数：" prop="collectTimes">
            <div class="width-per-50">
              <el-input v-model="action.collectTimes" @keyup.native="action.collectTimes = checkInputPositiveNum(action.collectTimes)" maxlength="10">
                <template slot="append">次</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item v-if="action.actionType == 30 && action.releaseType == 1" label="发放次数：" prop="releaseTimes">
            <div class="width-per-50">
              <div>
                <el-radio v-model="action.releaseTimes" @change="changeReleaseTimes" label="1">一次</el-radio>活动期间，符合条件的顾客仅发放一次
                <div class="font-12">活动开始日自动发放给当前符合条件的顾客。</div>
              </div>
              <div>
                <el-radio v-model="action.releaseTimes" @change="changeReleaseTimes" label="2">每月发放</el-radio>活动期间，在每个自然月的
                <el-select v-model="action.releaseMonthDay" :disabled="releaseMonthDayDisabled" placeholder="请选择" style="width: 100px;">
                  <el-option v-for="(item, index) in 31" :key="item" :label="item + '号'" :value="item"></el-option>
                  <el-option :key="0" label="最后一天" :value="0"></el-option>
                </el-select>
                发放一次
              </div>
              <div>
                <el-radio v-model="action.releaseTimes" @change="changeReleaseTimes" label="3">每周发放</el-radio>活动期间，在每周的
                <el-select v-model="action.releaseWeekDay" :disabled="releaseWeekDayDisabled" placeholder="请选择" style="width: 100px;">
                  <el-option v-for="(item, index) in weekDays" :key="index+1" :label="item" :value="index+1"></el-option>
                </el-select>
                发放一次
              </div>
              <div><el-radio v-model="action.releaseTimes" @change="changeReleaseTimes" label="4">手动发放</el-radio>活动期间，在券活动列表点击“发放”按钮进行发放</div>
            </div>
          </el-form-item>
          <el-form-item label="优惠券：" prop="coupons">
            <div class="width-per-50">
              <el-button type="text" @click="selectCouponVisible=true">选择优惠券</el-button>
            </div>
          </el-form-item>
        </div>
        <div class="height-20"></div>
      </el-form>
    </div>
    <div v-if="editFlag == 1" class="bottom-bar">
      <el-button @click="goActionList">返回</el-button>
      <el-button type="primary" @click="saveAction">创建</el-button>
    </div>
    <el-dialog title="选择优惠券" :visible.sync="selectCouponVisible" :close-on-press-escape="true" width="1000px">
      <coupon-select :coupons="action.coupons" v-on:setCoupon="setCoupon"></coupon-select>
    </el-dialog>
    <el-dialog title="选择商品" :visible.sync="selectGoodsVisible" :close-on-press-escape="true" width="850px">
      <goods-select :goodsIds="action.goodsIds" v-on:saveGoodsIds="saveGoodsIds"></goods-select>
    </el-dialog>
    <el-dialog title="微客选择器" :visible.sync="selectMemberVisible" :close-on-press-escape="true" width="750px">
      <member-select :memberIds="action.memberIds" v-on:saveMemberIds="saveMemberIds"></member-select>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.bgc-default{
  min-height: calc(100vh - 50px);
  box-sizing: border-box;
  h2{
    font-size: 20px;
    color: #666;
    line-height: 1;
    margin: 0 0 20px;
    font-weight: unset;
  }
  .bottom-bar{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 110px;
    position: fixed;
    left: 0;
    bottom: 0;
    width: calc(100% - 20px);
    box-shadow: 0 -2px 12px #eee;
    background-color: white;
    .el-button{
      width: 100px;
      height: 40px;
      line-height: 40px;
      padding: unset;
      text-align: center;
    }
    .el-button+.el-button{
      margin-left: 30px;
    }
  }
}
  .div-styls{
    margin-top: 30px;
    margin-bottom: 20px;
  }
  .mini-pic {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }
  .width-per-50{
    width: 48%;
    // margin-left: 1%!important;
    margin-right: 1%!important;
    background: #fff;
  }
</style>

<script>
  import { getAction, saveAction } from '@/api/coupon/action'
  import { getDictByGroupName } from '@/api/common/common'
  import elDragDialog from '@/directive/el-dragDialog'
  import CouponSelect from './components/CouponSelect'
  import GoodsSelect from '../../components/GoodsSelect'
  import MemberSelect from '../../components/member-select'
  import Tinymce from '@/components/Tinymce'

  export default {
    directives: {
      // 拖动窗口
      elDragDialog
    },
    components: {
      Tinymce, CouponSelect, GoodsSelect, MemberSelect
    },
    data() {
      return {
        toolbar: ['bold italic underline forecolor bullist numlist undo redo'],
        dict: {},
        action: {
          enterpriseId: this.getEnterpriseId(),
          actionStatus: '0',
          actionType: '0',
          actionName: '',
          fullAmount: '',
          actionTimeArray: [],
          buyType: '1',
          usedFlag: '1',
          customerType: '1',
          releaseType: '1',
          collectTimes: '',
          releaseTimes: '1',
          releaseMonthDay: 1,
          releaseWeekDay: 1,
          goodsIds: [],
          coupons: [],
          memberIds: []
        },
        weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        selectCouponVisible: false,
        selectGoodsVisible: false,
        selectMemberVisible: false,
        buyTypeGoodsDisabled: true,
        releaseMonthDayDisabled: true,
        releaseWeekDayDisabled: true,
        editFlag: '0',
        rules: {
          actionName: [
            { required: true, message: '活动名称不能为空', trigger: 'blur' }
          ],
          actionTimeArray: [
            { required: true, message: '活动时间不能为空', trigger: 'blur' }
          ],
          coupons: [
            { required: true, message: '请选择券', trigger: 'blur' }
          ],
          buyType: [
            { required: true, message: '发放条件不能为空', trigger: 'blur' }
          ],
          customerType: [
            { required: true, message: '发放人群不能为空', trigger: 'blur' }
          ],
          releaseType: [
            { required: true, message: '发放方式不能为空', trigger: 'blur' }
          ],
          collectTimes: [
            { required: true, message: '每人限领次数不能为空', trigger: 'blur' }
          ],
          releaseTimes: [
            { required: true, message: '发放次数不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    // 初始化页面
    created() {
      getDictByGroupName('ProjectOrderDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      this.init()
    },
    mounted() {
    },
    methods: {
      init() {
        const queryParams = this.getCurrentPage().query
        this.editFlag = queryParams.editFlag
        this.action.actionType = queryParams.actionType
        if (queryParams.actionId) {
          getAction(queryParams.actionId).then(response => {
            if (response.isError) {
              return
            }
            Object.assign(this.action, response.data)
            this.action.actionStatus = this.action.actionStatus.toString()
            this.action.actionType = this.action.actionType.toString()
            this.action.actionTimeArray.push(this.action.actionStartTime)
            this.action.actionTimeArray.push(this.action.actionEndTime)
            this.action.buyType = this.action.buyType ? this.action.buyType.toString() : ''
            this.buyTypeGoodsDisabled = this.action.buyType * 1 !== 3
            console.log(this.action.usedFlag)
            this.action.usedFlag = this.action.usedFlag ? this.action.usedFlag.toString() : '0'
            this.action.customerType = this.action.customerType ? this.action.customerType.toString() : ''
            this.action.releaseType = this.action.releaseType ? this.action.releaseType.toString() : ''
            this.action.releaseTimes = this.action.releaseTimes ? this.action.releaseTimes.toString() : ''
            this.$bus.$emit('setCoupon', this.action.coupons)
            this.$bus.$emit('setGoodsIds', this.action.goodsIds)
            this.$bus.$emit('setMemberIds', this.action.memberIds)
            this.changeBuyType()
            this.changeReleaseTimes()
          })
        }
      },
      setCoupon(coupons) {
        this.action.coupons = coupons
        this.selectCouponVisible = false
      },
      saveGoodsIds(goodsIds) {
        this.action.goodsIds = goodsIds
        this.selectGoodsVisible = false
      },
      saveMemberIds(memberIds) {
        this.action.memberIds = memberIds
        this.selectMemberVisible = false
      },
      saveAction() {
        let validateResult = true
        const checkArrays = ['actionName', 'actionTimeArray']
        if (this.action.actionType * 1 === 20) {
          checkArrays.push('buyType')
        }
        if (this.action.actionType * 1 === 30) {
          checkArrays.push('customerType')
          checkArrays.push('releaseType')
        }
        this.$refs.action.validateField(checkArrays, (valid) => {
          if (valid) {
            validateResult = false
          }
        })
        if (!validateResult) {
          return
        }
        if (this.action.actionType * 1 === 20) {
          if (this.action.buyType * 1 === 2 && !this.action.fullAmount) {
            this.$message.error('请输入满减金额')
            return
          }
          if (this.action.buyType * 1 === 2 && this.action.fullAmount * 1 <= 0) {
            this.$message.error('满减金额金额必须大于0')
            return
          }
          if (this.action.buyType * 1 === 3 && !this.action.goodsIds.length) {
            this.$message.error('请先选择商品')
            return
          }
        }
        if (this.action.actionType * 1 === 30) {
          if (this.action.releaseType * 1 === 2 && !this.action.collectTimes) {
            this.$message.error('每人限领次数不能为空')
            return
          }
          if (this.action.customerType * 1 === 4) {
            if (this.action.memberIds === null || this.action.memberIds.length === 0) {
              this.$message.error('指定的微客不能为空')
              return
            }
          }
        }
        if (!this.action.coupons.length) {
          this.$message.error('请选择券')
          return
        }

        this.action.actionStartTime = this.action.actionTimeArray[0]
        this.action.actionEndTime = this.action.actionTimeArray[1]
        saveAction(this.action).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功！',
            type: 'success'
          })
          this.$router.push({ path: '/sell-promotion/coupon/action', query: { actionType: this.action.actionType }})
        })
      },
      goActionList() {
        this.$router.push({ path: '/sell-promotion/coupon/action', query: { actionType: this.action.actionType }})
      },
      changeBuyType() {
        this.buyTypeGoodsDisabled = this.action.goodsRange * 1 === 3
      },
      changeReleaseTimes() {
        if (this.action.releaseTimes * 1 === 2) {
          this.releaseMonthDayDisabled = false
          this.releaseWeekDayDisabled = true
        }
        if (this.action.releaseTimes * 1 === 3) {
          this.releaseMonthDayDisabled = true
          this.releaseWeekDayDisabled = false
        }
        if (this.action.releaseTimes * 1 === 1 || this.action.releaseTimes * 1 === 4) {
          this.releaseMonthDayDisabled = true
          this.releaseWeekDayDisabled = true
        }
      }
    }
  }

</script>
